package com.xc.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 *
 * 通用返回类型class
 * Created by xiongcan on 2017/12/26.
 *
 *  此类是一个序列化的类，里面的public的方法都会返回给前端，如果不需要用jsonignore除去
 *
 *  JsonSerialize 是去除null值返回给前端
 */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {

    private int status;

    private String msg;

    private T data;

//    构造1
    private ServerResponse(int status){
        this.status = status;
    }
//    构造2
    private ServerResponse(int status , T data){
        this.status = status;
        this.data = data;
    }
//    构造3
    private ServerResponse(int status , String msg){
        this.status = status;
        this.msg = msg;
    }
//    构造4
    private ServerResponse(int status , String msg , T data){
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

//    PS:如果构造2和构造3 后面的范型是string类型的时候，会调用哪个构造    psvm
    public static void main(String[] args) {
        ServerResponse serverResponse = new ServerResponse(1 , new Object());
        ServerResponse serverResponse1 = new ServerResponse(1 , "abc");
        System.out.print("ServerResponse");
    }


//    如果是 string类型的参数则会调用构造3，所以如果需要返回出去的data是string类型的，则需要用如下的方法去重新构造

    //    首先开放字段的get方法
    @JsonIgnore
    public boolean isSuccess(){
        return this.status == ResponseCode.SUCCESS.getCode();
    }
    public int getStatus(){
        return status;
    }
    public T getData(){
        return data;
    }
    public String getMsg(){
        return msg;
    }

    //    其次开放静态方法
    public static <T> ServerResponse<T> createBySuccess(){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
    public static <T> ServerResponse<T> createBySuccessMsg(String msg){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static <T> ServerResponse<T> createBySuccess(T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode() , data);
    }
    public static <T> ServerResponse<T> createBySuccess(String msg , T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), msg , data);
    }

    public static <T> ServerResponse<T> createByError(){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode() , ResponseCode.ERROR.getMsg());
    }
    public static <T> ServerResponse<T> createByErrorMsg(String errormsg){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode() , errormsg);
    }
    public static <T> ServerResponse<T> createByErrorCodeMsg(int errorcode , String errormsg){
        return new ServerResponse<T>(errorcode , errormsg);
    }


}
